import { Injectable, Logger, ConflictException, InternalServerErrorException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DeepPartial } from 'typeorm';
import { BaseService } from '../../../common/services/base.service';
import { User } from '../entities/user.entity';
import { UserLogService } from '../../user-log/services/user-log.service';
import { CreateUserDto } from '../dto/create-user.dto';
import { UpdateUserDto } from '../dto/update-user.dto';
import { QueryUserDto } from '../dto/query-user.dto';

@Injectable()
export class UserService extends BaseService<User> {
  private readonly logger = new Logger(UserService.name);

  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    private readonly userLogService: UserLogService,
  ) {
    super(userRepository);
  }

  /**
   * 获取资源类型名称
   */
  public getResourceType(): string {
    return 'user';
  }

  /**
   * 获取资源名称
   */
  public getResourceName(): string {
    return '用户';
  }

  /**
   * 记录创建日志
   */
  public async logCreate(userId?: string, resourceId?: string): Promise<void> {
    if (!resourceId) return;
    
    try {
      if (userId) {
        // 有用户ID时，记录具体用户的操作
        const currentUser = await this.userRepository.findOne({ where: { id: userId } });
        if (currentUser) {
          await this.userLogService.logUserCreate(
            userId,
            currentUser.username,
            resourceId,
          );
        }
      }
    } catch (error) {
      this.logger.error('记录用户创建日志失败', error.stack);
    }
  }

  /**
   * 记录更新日志
   */
  public async logUpdate(userId?: string, resourceId?: string): Promise<void> {
    if (!resourceId) return;
    
    try {
      if (userId) {
        // 有用户ID时，记录具体用户的操作
        const currentUser = await this.userRepository.findOne({ where: { id: userId } });
        if (currentUser) {
          await this.userLogService.logUserUpdate(
            userId,
            currentUser.username,
            resourceId,
          );
        }
      }
    } catch (error) {
      this.logger.error('记录用户更新日志失败', error.stack);
    }
  }

  /**
   * 记录删除日志
   */
  public async logDelete(userId?: string, resourceId?: string): Promise<void> {
    if (!resourceId) return;
    
    try {
      if (userId) {
        // 有用户ID时，记录具体用户的操作
        const currentUser = await this.userRepository.findOne({ where: { id: userId } });
        if (currentUser) {
          await this.userLogService.logUserDelete(
            userId,
            currentUser.username,
            resourceId,
          );
        }
      }
    } catch (error) {
      this.logger.error('记录用户删除日志失败', error.stack);
    }
  }

  /**
   * 记录批量删除日志
   */
  public async logBatchDelete(userId?: string, resourceIds?: string[]): Promise<void> {
    if (!resourceIds || resourceIds.length === 0) return;
    
    try {
      if (userId) {
        // 有用户ID时，记录具体用户的操作
        const currentUser = await this.userRepository.findOne({ where: { id: userId } });
        if (currentUser) {
          await this.userLogService.logUserBatchDelete(
            userId,
            currentUser.username,
          );
        }
      }
    } catch (error) {
      this.logger.error('记录用户批量删除日志失败', error.stack);
    }
  }

  /**
   * 根据用户名查找用户
   */
  async findByUsername(username: string): Promise<User | null> {
    return await this.userRepository.findOne({
      where: { username, isDeleted: false },
      relations: ['role'],
    });
  }

  /**
   * 检查用户名是否存在
   */
  async isUsernameExists(username: string): Promise<boolean> {
    const count = await this.userRepository.count({
      where: { username, isDeleted: false },
    });
    return count > 0;
  }

  /**
   * 创建用户（覆盖基类create）：
   * - 先进行用户名唯一性校验
   * - 捕获数据库唯一键冲突并抛出 409
   * - 其他错误抛出 500，由全局过滤器统一处理
   */
  async create(data: CreateUserDto, userId?: string): Promise<boolean> {
    // 预检查：避免无谓的数据库异常
    const usernameExists = await this.isUsernameExists(data.username);
    if (usernameExists) {
      throw new ConflictException('用户名已存在');
    }

    try {
      // 调用基类的create方法，确保时间字段被正确设置
      return await super.create(data as DeepPartial<User>, userId);
    } catch (error: any) {
      // MySQL 唯一键冲突
      if (error?.code === 'ER_DUP_ENTRY' || error?.errno === 1062) {
        throw new ConflictException('用户名已存在');
      }
      this.logger.error('创建用户失败', error?.stack);
      throw new InternalServerErrorException('用户创建失败');
    }
  }

  /**
   * 根据条件查找所有用户
   */
  async findAllWithConditions(queryDto: QueryUserDto): Promise<User[]> {
    const queryBuilder = this.userRepository.createQueryBuilder('user')
      .leftJoinAndSelect('user.role', 'role')
      .where('user.isDeleted = :isDeleted', { isDeleted: false });

    // 添加查询条件
    if (queryDto.username) {
      queryBuilder.andWhere('user.username LIKE :username', { 
        username: `%${queryDto.username}%` 
      });
    }

    if (queryDto.nickname) {
      queryBuilder.andWhere('user.nickname LIKE :nickname', { 
        nickname: `%${queryDto.nickname}%` 
      });
    }

    if (queryDto.phone) {
      queryBuilder.andWhere('user.phone LIKE :phone', { 
        phone: `%${queryDto.phone}%` 
      });
    }

    if (queryDto.roleId) {
      queryBuilder.andWhere('user.roleId = :roleId', { 
        roleId: queryDto.roleId 
      });
    }

    // 按创建时间倒序排列
    queryBuilder.orderBy('user.createdAt', 'DESC');

    return await queryBuilder.getMany();
  }
} 